﻿using System;
using System.Collections.Generic;
using AuthRes = BotonJXC.Entity.AuthRes;
using AuthResDAO = BotonJXC.DAO.AuthResDAO;
using BotonJXC.Util;
using NHibernate.Criterion;

namespace BotonJXC.BLL
{
    public class AuthResBLL : BaseBLL<AuthResDAO, AuthRes, int>
    {
        public AuthResBLL()
        {

        }
        public IList<AuthRes> FindByUserId(int userId)
        {
            return base.Dao.FindByUserId(userId);
        }
        public IList<AuthRes> FindByRoleId(int roleId)
        {
            return base.Dao.FindByRoleId(roleId);
        }
        public TreeDataNode<AuthRes> FindByRoleIdToTree(int roleId)
        {
            IList<AuthRes> list = FindByRoleId(roleId);
            return ToTree(list);
        }
        public TreeDataNode<AuthRes> FindAllToTree()
        {
            IList<AuthRes> list = Dao.Find(new ICriterion[] { }, new Order("AuthResPath", true), -1, -1);
            return ToTree(list);
        }

        public TreeDataNode<AuthRes> ToTree(IList<AuthRes> list)
        {
            IDictionary<string, TreeDataNode<AuthRes>> dict = new Dictionary<string, TreeDataNode<AuthRes>>();
            TreeDataNode<AuthRes> tree = new TreeDataNode<AuthRes>();
            foreach (AuthRes ar in list)
            {
                TreeDataNode<AuthRes> arNode = getParentNode(dict, ar.AuthResPath);
                TreeDataNode<AuthRes> arNode2 = new TreeDataNode<AuthRes>(ar);
                dict.Add(ar.AuthResId.ToString(), arNode2);
                if (arNode == null)
                    tree.Add(arNode2);
                else
                    arNode.Add(arNode2);
            }
            return tree;
        }

        public TreeDataNode<AuthRes> FindByUserIdToTree(int userId)
        {

            IList<AuthRes> list = FindByUserId(userId);
            return ToTree(list);
        }

        private TreeDataNode<AuthRes> getParentNode(IDictionary<string, TreeDataNode<AuthRes>> nodes, string path)
        {
            string[] paths = path.Split('-');
            if (paths.Length > 2)
            {
                TreeDataNode<AuthRes> ar = null;
                nodes.TryGetValue(paths[paths.Length - 3], out ar);
                return ar;
            }
            return null;
        }
    }
}
